package com.hc.controller;

import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.common.service.RedisService;
import com.hc.constant.RedisConst;
import com.hc.constant.SkuConst;
import com.hc.domain.City;
import com.hc.domain.Country;
import com.hc.domain.Province;
import com.hc.ex.GlobalException;
import com.hc.service.CategoryService;
import com.hc.service.CityService;
import com.hc.service.CountryService;
import com.hc.service.ProvinceService;
import com.hc.service.SkuService;
import com.hc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hecai
 * @date 2021/12/13 9:16
 */
@Slf4j
@RestController
@RequestMapping("/init")
public class InitController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private UserService userService;
    @Resource
    private SkuService skuService;

    @GetMapping("/redis")
    public Result initRedis() {
        try {
            //初始化首页所有的类别（二级列表）
            categoryService.listAllCategories("tree", true);
            //初始化省
            initProvinceList();
            //初始化市
            initCityList();
            //初始化县区
            initCountryList();
            //初始化时缓存最活跃的用户信息，以后用记一登录就将用户信息保存到Redis中，退出就将用户信息从Redis中删除
            userService.findTopActiveUsers(RedisConst.CACHED_ACTIVE_USER_AMOUNT);

            //初始化首页数据
            //初始化轮播图
            skuService.selectAds(5, SkuConst.Type.CAROUSEL, RedisConst.Index.CAROUSEL, true);
            //初始化分隔
            skuService.selectAds(4, SkuConst.Type.DIVIDER, RedisConst.Index.DIVIDER, true);
            //初始化广告
            skuService.selectAds(5, SkuConst.Type.AD, RedisConst.Index.AD, true);
            //初始化推荐
            skuService.selectRecommendOrPromotionSku(5, SkuConst.Type.Recommend, RedisConst.Index.RECOMMEND, true);
            //初始化促销
            skuService.selectRecommendOrPromotionSku(5, SkuConst.Type.Promotion, RedisConst.Index.PROMOTION, true);
            //初始化楼层：类别+sku
            skuService.selectCategoryWidthSku(4, 5, 8, RedisConst.Index.CATEGORY_WITH_SKU, true);
        } catch (Exception e) {
            throw new GlobalException(400, e.getMessage());
        }

        return ResultUtil.success("系统初始化成功");
    }

    @Resource
    private RedisService<Province> proviceRedisService;
    @Resource
    private ProvinceService provinceService;

    /**
     * 将数据库中所有的省信息读取到Redis
     */
    private void initProvinceList() {
        List<Province> provinceList = provinceService.findAllProvince("all", true);
        provinceList.forEach(item -> {
            proviceRedisService.set(RedisConst.PROVINCE + "::" + item.getId(), item, -1L);
        });
    }

    /**
     * 用来在redis中缓存：键-市编号，值-省编号
     */
    @Resource
    private RedisService<City> cityRedisService;

    /**
     * 用来在redis中缓存：键-省编号，值-省下所有的市
     */
    @Resource
    private RedisService<List<City>> provinceCityRedisService;

    @Resource
    private CityService cityService;

    /**
     * 将数据库中所有的市信息读取到Redis
     */
    private void initCityList() {
        List<City> cityList = cityService.list(null);

        Map<Integer, List<City>> cityMap = new HashMap<>();
        for (City city : cityList) {
            //以set的方式缓存Country信息到Redis
            cityRedisService.set(RedisConst.CITY + "::" + city.getId(), city, -1L);

            if (cityMap.containsKey(city.getProvinceId())) {
                cityMap.get(city.getProvinceId()).add(city);
            } else {
                ArrayList<City> tmp = new ArrayList<>();
                tmp.add(city);
                cityMap.put(city.getProvinceId(), tmp);
            }
        }

        // System.out.println(JsonUtil.obj2String(cityMap));

        for (Map.Entry<Integer, List<City>> entry : cityMap.entrySet()) {
            //以hash的方式缓存城市id及其所辖的Country列表到Redis
            List<City> cityList1 = entry.getValue();
            //排序
            cityList1.sort((item1, item2) -> {
                int t1 = item1.getPriority() == null ? 0 : item1.getPriority();
                int t2 = item2.getPriority() == null ? 0 : item2.getPriority();
                return t2 - t1;
            });
            provinceCityRedisService.set(RedisConst.PROVINCE_CITY + "::" + entry.getKey(), cityList1, -1L);
        }
    }

    @Resource
    private RedisService<Country> countryRedisService;

    @Resource
    private RedisService<List<Country>> cityCountryRedisService;

    @Resource
    private CountryService countryService;

    /**
     * 将数据库中所有的市信息读取到Redis
     */
    private void initCountryList() {
        List<Country> countryList = countryService.list(null);

        Map<Integer, List<Country>> cityMap = new HashMap<>();

        for (Country country : countryList) {
            //以set的方式缓存Country信息到Redis
            countryRedisService.set(RedisConst.COUNTRY + "::" + country.getId(), country, -1L);

            if (cityMap.containsKey(country.getCityId())) {
                cityMap.get(country.getCityId()).add(country);
            } else {
                ArrayList<Country> tmp = new ArrayList<>();
                tmp.add(country);
                cityMap.put(country.getCityId(), tmp);
            }
        }

        // System.out.println(JsonUtil.obj2String(cityMap));

        for (Map.Entry<Integer, List<Country>> entry : cityMap.entrySet()) {
            //以hash的方式缓存城市id及其所辖的Country列表到Redis
            cityCountryRedisService.set(RedisConst.CITY_COUNTRY + "::" + entry.getKey(), entry.getValue(), -1L);
        }
    }

}